/*
 * Copyright (C) 2012 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.woyou.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;

import retrofit.converter.ConversionException;
import retrofit.converter.Converter;
import retrofit.mime.MimeUtil;
import retrofit.mime.TypedInput;
import retrofit.mime.TypedOutput;

/**
 * A {@link Converter} which uses GSON for serialization and deserialization of entities.
 *
 * @author Jake Wharton (jw@squareup.com)
 */
public class GsonConverter implements Converter {
  private static final String TAG = "GsonConverter";
private final Gson gson;
  private String charset;

  /**
   * Create an instance using the supplied {@link Gson} object for conversion. Encoding to JSON and
   * decoding from JSON (when no charset is specified by a header) will use UTF-8.
   */
  public GsonConverter(Gson gson) {
    this(gson, "UTF-8");
  }

  /**
   * Create an instance using the supplied {@link Gson} object for conversion. Encoding to JSON and
   * decoding from JSON (when no charset is specified by a header) will use the specified charset.
   */
  public GsonConverter(Gson gson, String charset) {
    this.gson = gson;
    this.charset = charset;
  }

  @Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
    String charset = this.charset;
    if (body.mimeType() != null) {
      charset = MimeUtil.parseCharset(body.mimeType(), charset);
    }
    BufferedReader reader = null;
    try {
		reader = new BufferedReader(
					new InputStreamReader(body.in()));
//		StringBuilder sb = new StringBuilder();
//		String line = null;
//		while ((line = reader.readLine()) != null) {
//			sb.append(line);
//		} 
//		String str = sb.toString();
//		str.length();
		
		
//		String str = "{\"code\":1,\"msg\":\"成功\"," +
//				"\"page\":0,\"list\":[{\"sId\":\"SHDP414\",\"sName\":" +
//				"\"蝶依花坊152\",\"phone\":\"13391310602\",\"avgReceive\":" +
//				"\"1\",\"avgSend\":\"1\",\"picUrl\":" +
//				"\"http://photo.ideliver1.cn/Upload/Shop/DE07BD0D-67C2-467E-AC36-0EB01B7CC161.jpg\",\"salesUrl\":\"1\",\"score\":\"1\",\"lat\":\"31.20498900\",\"lng\":\"121.47817900\",\"address\":\"黄浦区蒙自路274号\",\"notice\":\"全城范围均可派送\",\"salesQty\":\"100\",\"commentsNum\":0,\"distance\":79.53325193994,\"status\":1,\"spending\":\"0.00\"},{\"sId\":\"SHDP236\",\"sName\":\"台北牛肉面152\",\"phone\":\"021-53069776\",\"avgReceive\":\"1\",\"avgSend\":\"1\",\"picUrl\":\"http://photo.ideliver1.cn/Upload/Shop/8CBBD41A-5D71-40FE-8EF6-3EADE08335E2.jpg\",\"salesUrl\":\"1\",\"score\":\"1\",\"lat\":\"31.20683300\",\"lng\":\"121.47778600\",\"address\":\"卢湾区蒙自路223号\",\"notice\":\"\",\"salesQty\":\"100\",\"commentsNum\":0,\"distance\":287.96896360254,\"status\":1,\"spending\":\"50.00\"}],\"ms\":3.3}";
//		str.length();
//		Log.i(TAG, "res:"+str);
//		Object fromJson = gson.fromJson(str, type);
//		fromJson.toString();
		
      return gson.fromJson(reader, type);
    } catch (IOException e) {
      throw new ConversionException(e);
    } catch (JsonParseException e) {
      throw new ConversionException(e);
    } finally {
      if (reader != null) {
        try {
        	reader.close();
        } catch (IOException ignored) {
        }
      }
    }
  }

  @Override public TypedOutput toBody(Object object) {
    try {
      return new JsonTypedOutput(gson.toJson(object).getBytes(charset), charset);
    } catch (UnsupportedEncodingException e) {
      throw new AssertionError(e);
    }
  }

  private static class JsonTypedOutput implements TypedOutput {
    private final byte[] jsonBytes;
    private final String mimeType;

    JsonTypedOutput(byte[] jsonBytes, String encode) {
      this.jsonBytes = jsonBytes;
      this.mimeType = "application/json; charset=" + encode;
    }

    @Override public String fileName() {
      return null;
    }

    @Override public String mimeType() {
      return mimeType;
    }

    @Override public long length() {
      return jsonBytes.length;
    }

    @Override public void writeTo(OutputStream out) throws IOException {
      out.write(jsonBytes);
    }
  }
}
